var app = getApp();
var that;
Page({
  data: {
    selectedAllStatus:false, //全部选中
    carts: [],  //购物车离里的商品
    level:0,
    total1:0,
    total2:0,
    iscoudan:false,
    free_shopping_money:0  //满xxx元免邮
  },
 
  bindMinus: function (e) { // 减号
  // console.log(e)
  var index = e.currentTarget.dataset.index;
  var goodsid = e.currentTarget.dataset.goodsid;
  var id = e.currentTarget.dataset.id;
    if (that.data.carts.list[index].total> 1) { 
      that.data.carts.list[index].total = parseInt(that.data.carts.list[index].total)-1;
      that.sum()
      that.change_num(id, goodsid, that.data.carts.list[index].total);
     }
    this.setData({ carts: that.data.carts });  
  },

  bindPlus: function (e) { //加号
    var index = e.currentTarget.dataset.index;
    var goodsid = e.currentTarget.dataset.goodsid;
    var id = e.currentTarget.dataset.id;
    if (that.data.carts.list[index].total < that.data.carts.list[index].stock) {
      that.data.carts.list[index].total = parseInt(that.data.carts.list[index].total)+1;
      that.sum()
      that.change_num(id, goodsid, that.data.carts.list[index].total);
    }else{app.toast_up('库存不足！')}
    this.setData({ carts: that.data.carts });  
  }, 
  to_detail:function(e){
    // console.log(e)
    wx.navigateTo({
      url: './goods_detail?productId=' + e.currentTarget.dataset.goodsid
    })
  },
  bindCheckbox: function (e) { 
    /*绑定点击事件，将checkbox样式改变为选中与非选中*/
    //拿到下标值，以在carts作遍历指示用
    var index = parseInt(e.currentTarget.dataset.index);
    //原始的icon状态
    console.info('index: ' + e.currentTarget.dataset.index);
    if (that.data.carts.list[index].selected){
      that.data.carts.list[index].selected=false
    } else { that.data.carts.list[index].selected = true}

    that.setData({ selectedAllStatus:true})        //判断是否全部选中
    for (var i = 0; i < that.data.carts.list.length;i++){
      if (that.data.carts.list[i].selected!=true){
        that.setData({ selectedAllStatus: false })
      }
    }
    that.setData({ carts: that.data.carts});
    that.sum()
  },

  bindSelectAll: function () { // 全选状态 
    for (var i = 0; i < that.data.carts.list.length; i++) {
      that.data.carts.list[i].selected = !that.data.selectedAllStatus;
    }
    that.setData({
       selectedAllStatus: !that.data.selectedAllStatus, carts: that.data.carts });
    that.sum()
  },
  back:function(){
    wx.switchTab({
      url: './shop'
    })
  },
  bindCheckout: function () {  //立刻结算
    // 初始化toastStr字符串
    var toastStr = '';
    // 遍历取出已勾选的cid
    for (var i = 0; i < that.data.carts.list.length; i++) {
      if (that.data.carts.list[i].selected==true) {
        toastStr += that.data.carts.list[i].id;
        toastStr += '|';
      }
    }
    if (toastStr == '') {
      wx.showToast({
        title: '请选择商品！',
        duration: 2000
      });
      return false;
    }
    

    toastStr = toastStr.substring(0, toastStr.length-1)
    //存回data
    if (app.data.person_msg_rr.level < 1 && app.data.iswarm == 0) {//若非会员则提示注册会员
      wx.navigateTo({ url: '../member/application_member' })
      return;
    }
    wx.navigateTo({
      url: './shop_order?cartids=' + toastStr,
    })
  },

  sum: function () {
    var carts = that.data.carts.list;
    // 计算总金额
    var t1 = 0;
    var t2 = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected==true) {
        t1 += carts[i].total * parseFloat(carts[i].marketprice); 
        t2 += carts[i].total * parseFloat(carts[i].productprice);
      }
    }
    this.setData({ total1: t1,  total2: t2,}); 

    if ((parseFloat(t1) > that.data.free_shopping_money && that.data.level > 0) || (parseFloat(t2) > that.data.free_shopping_money && that.data.level==0)){  //判断是否显示上方的凑单
      that.setData({iscoudan:false})
    } else { that.setData({ iscoudan: true })}
    if (parseFloat(t1) == 0 && parseFloat(t2) == 0) { that.setData({ iscoudan: false })}
  },

  onLoad: function (options) {
    that=this;
    that.setData({level:app.data.person_msg_rr.level})
    that.get_car();
  },

  onShow: function () {
    var that = this;
   
    
    if (app.data.iswarm == 1){
      app.data.iswarm = 2
      that.bindCheckout()
    }
    
  },
  get_car:function(){
    wx.showLoading({
      title: '加载中....',
    })

    app.req(app.local_url + "do=shop&p=cart", { "od": app.data.openid,'shop_id':wx.getStorageSync('shop_id') }, function (res) {
      console.log(res)
      if (res.status == 1) {
        wx.hideLoading();
        var dispatch = res.result.dispatch;
        for (var i = 0; i < dispatch.length;i++){
          if (dispatch[i].dispatchtype==0){
            that.setData({ free_shopping_money: parseFloat(dispatch[i].secondprice) });
            console.log(that.data.free_shopping_money);
          }
        }
        that.setData({carts:res.result})
        that.sum();//每次购物车变动后重新算钱
      } else if (res.status == 0) {
        app.toast_up(res.result)
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.get_car()
          }
        })
      }
    })
  },
  removeShopCard: function (e) {
    var cardId = parseInt(e.currentTarget.dataset.id);
    var ids=[];
    ids.push(cardId);
    // console.log(ids)
    // return;
    wx.showModal({
      title: '提示',
      content: '您确定要删除此商品吗?',
      success: function (re) {
        if (re.confirm){
          app.req(app.local_url + "do=shop&p=cart&op=remove", { "od": app.data.openid,"ids":ids }, function (res) {
            console.log(res)
            if (res.status == 1) {
              that.get_car();
              that.setData({ selectedAllStatus:false });//重新获取时全选为空
            } else if (res.status == 0) {
              app.toast_up(res.result)
            } else {
              app.modal("错误提示", "网络错误，是否重试？", function (re) {
                if (re) {
                  that.removeShopCard(e)
                }
              })
            }
          })
        }
      }
    });
  },
  change_num: function (id,goodsid,num) {
    app.req(app.local_url + "do=shop&p=cart&op=updatenum", { "od": app.data.openid, "id": id, "goodsid": goodsid, "total": num, }, function (res) {
      console.log(res)
            if (res.status == 1) {
            } else if (res.status == 0) {
              app.toast_up(res.result)
            } else {
              app.modal("错误提示", "网络错误，是否重试？", function (re) {
                if (re) {
                  that.change_num(id, goodsid, num)
                }
              })
            }
          })
  },
  coudan:function(){
    wx.switchTab({ url: '../shop/shop', }) //跳到商城首页
  }
})
